using Pathfinding.Serialization.JsonFx;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

namespace Artifact.Unity.Config
{
    public delegate void ReadFileComplete(List<string[]> list);
    public delegate void ReadFileStringComplete(String text);

    public class FileReader
    {
        public static void ReadCSV(string fileName,ReadFileComplete _complete)
        {
            Asset.AssetBundleManager.Instance.LoadAssetAsync(fileName, (o2) =>
            {
                TextAsset asset2_ = o2.Require(null) as TextAsset;
                string[] lines = asset2_.text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine = null;
                List<string[]> list = new List<string[]>();
                for (int i = 0; i < lines.Length; i++)
                {
                    if (i < 4)
                    {
                        continue;
                    }
                    strLine = lines[i];
                    if (strLine.Length < 2)
                    {
                        continue;
                    }
                    strLine = strLine.Replace("\\r\\n", "\r\n");
                    aryLine = strLine.Split(';');
                    list.Add(aryLine);
                }
                if (_complete != null)
                    _complete(list);
            }, null);
        }

        public static void ReadString(string fileName, ReadFileStringComplete _complete)
        {
            Asset.AssetBundleManager.Instance.LoadAssetAsync(fileName, (o2) =>
            {
                TextAsset asset2_ = o2.Require(null) as TextAsset;
                if (_complete != null)
                    _complete(asset2_.text.ToString());
            }, null);
        }
    }

    public class ConfigLoader {
        public static Hashtable GlobalConfigTable = new Hashtable();
        public static Dictionary<string,string> I18nConfigTable = new Dictionary<string,string>();
        /// <summary>
        /// 技能数据
        /// <summary>
        public static Dictionary<object,ConfigSkillDataConfig> ConfigSkillDataConfigTable = new Dictionary<object,ConfigSkillDataConfig>();



        /// <summary>
        /// 全局
        /// <summary>
        public static object DeepGetGlobal(string key){
            return DeepGetGlobal(key,GlobalConfigTable);
        }

        private static object DeepGetGlobal(String key, IDictionary table){
            int index = key.IndexOf(".");
            string[] keys = null;
            if (index > 0)
            {
                keys = new string[] { key.Substring(0, index), key.Substring(index + 1, key.Length - (index + 1)) };
            }
            else {
                keys = new string[] { key };
            }

            object obj = null;
            if (keys.Length > 0){
                obj = table.Contains(keys[0]) ? table[keys[0]] : null;
            }
            if (keys.Length > 1){
                if (obj != null && obj is IDictionary)
                {
                    return DeepGetGlobal(keys[1],(IDictionary) obj);
                }
            }
            return obj;
        }

        /// <summary>
        /// I18N
        /// <summary>
        public static String GetI18nConfig(string key){
            if(I18nConfigTable.ContainsKey(key)){
                return I18nConfigTable[key];
            }else{
                return null;
            }
        }
        /// <summary>
        /// 技能数据
        /// <summary>
        public static ConfigSkillDataConfig GetConfigSkillDataConfig(object key){
            if(ConfigSkillDataConfigTable.ContainsKey(key)){
                return ConfigSkillDataConfigTable[key];
            }else{
                return null;
            }
        }

        public static void load() {
            // 读取离散文件
            FileReader.ReadString("Global.csv",(d) => {
                GlobalConfigTable = (Hashtable)JsonReader.Deserialize<Hashtable>(d);
            });

            // 读取国际化文件
            FileReader.ReadCSV("I18n.csv",(d)=>{
                foreach (string[] row in d)
                {
                    I18nConfigTable.Add(row[0], row[1]);
                }
            });

            FileReader.ReadCSV("ConfigSkillData.csv",(d) =>{
               foreach (string[] row in d)
               {
                   ConfigSkillDataConfig o = new ConfigSkillDataConfig(row);
                   ConfigSkillDataConfigTable.Add(o.Id, o);
               }
            });
        }

        public static void clear(){
            GlobalConfigTable.Clear();
            I18nConfigTable.Clear();
            ConfigSkillDataConfigTable.Clear();
        }
    }
    public static class ParseUtil
    {
        private static bool isEmpty(string str)
        {
            return str == null || str.Length == 0;
        }

        public static int ParseInt(string s)
        {
            if (isEmpty(s)) {
                return 0;
            }
            return int.Parse(s);
        }

        public static int[] ParseIntArray(string s)
        {
            if (isEmpty(s))
            {
                return new int[0];
            }
            string[] strs = s.Split('#');
            int[] ints = new int[strs.Length];
            for (int i = 0; i < ints.Length; i++)
            {
                ints[i] = int.Parse(strs[i]);
            }
            return ints;
        }

        public static int[][] ParseIntsArray(string s)
        {
            if (isEmpty(s))
            {
                return new int[0][];
            }
            string[] strs = s.Split('|');
            int[][] ints = new int[strs.Length][];
            for (int i = 0; i < strs.Length; i++)
            {
                ints[i] = ParseIntArray(strs[i]);
            }
            return ints;
        }

        public static string ParseStr(string s)
        {
            if (isEmpty(s))
            {
                return "";
            }
            return s;
        }

        public static string[] ParseStrArray(string s)
        {
            if (isEmpty(s))
            {
                return new string[0];
            }
            string[] strs = s.Split('#');
            return strs;
        }

        public static string[][] ParseStrsArray(string s)
        {
            if (isEmpty(s))
            {
                return new string[0][];
            }
            string[] strs = s.Split('|');
            string[][] strss = new string[strs.Length][];
            for (int i = 0; i < strs.Length; i++)
            {
                strss[i] = ParseStrArray(strs[i]);
            }
            return strss;
        }

        public static IDictionary ParseDictionary(IDictionary dict, string s)
        {
            if (isEmpty(s))
            {
                return dict;
            }
            // IDictionary list = (IDictionary)Activator.CreateInstance(dict.GetType(), true);//根据类型创建实例
            string[] strs = s.Split(',');
            for (int i = 0; i < strs.Length; i++)
            {
                string[] kv = strs[i].Split('=');
                Type keyType = dict.GetType().GenericTypeArguments[0];
                Type valType = dict.GetType().GenericTypeArguments[1];
                dict.Add(ParseObject(keyType, kv[0]), ParseObject(valType, kv[1]));
            }
            return dict;
        }

        public static IList ParseList(IList list, string s)
        {
            if (isEmpty(s))
            {
                return list;
            }
            // IList list = (IList)Activator.CreateInstance(dict.GetType(), true);//根据类型创建实例
            string[] strs = s.Split('|');
            for (int i = 0; i < strs.Length; i++)
            {
                Type type = list.GetType().GenericTypeArguments[0];
                list.Add(ParseObject(type, strs[i]));
            }
            return list;
        }

        public static Hashtable ParseJson(string s)
        {
            if (isEmpty(s))
            {
                return new Hashtable();
            }
            Hashtable hashtable = (Hashtable)JsonReader.Deserialize<Hashtable>(s);
            return hashtable;
        }

        public static object ParseObject(Type type, string str)
        {
            if (type.Name.StartsWith("Dictionary"))
            {
                IDictionary _dict = (IDictionary)Activator.CreateInstance(type, true);//根据类型创建实例
                return ParseDictionary(_dict, str);
            }
            else if (type.Name.StartsWith("List"))
            {
                IList _list = (IList)Activator.CreateInstance(type, true);//根据类型创建实例
                return ParseList(_list, str);
            }
            else if (type.Name.Equals("Int32"))
            {
                return ParseInt(str);
            }
            else if (type.Name.Equals("Int32[]"))
            {
                return ParseIntArray(str);
            }
            else if (type.Name.Equals("Int32[][]"))
            {
                return ParseIntsArray(str);
            }
            else if (type.Name.Equals("String"))
            {
                return ParseStr(str);
            }
            else if (type.Name.Equals("String[]"))
            {
                return ParseStrArray(str);
            }
            else if (type.Name.Equals("String[][]"))
            {
                return ParseStrsArray(str);
            }
            return null;
        }
    }


}